package com.yange.accountbook.ui

import android.app.DatePickerDialog
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.view.View
import com.google.gson.Gson
import com.yange.accountbook.databinding.MineFragmentLayoutBinding
import com.yange.accountbook.entity.UserInfoEntity
import com.yange.accountbook.net.Api
import com.yange.accountbook.net.BaseResponse
import com.yange.accountbook.net.api.RetrofitClient
import com.yange.accountbook.net.observable.RecObserver
import com.yange.accountbook.utils.StringUtils
import com.yange.accountbook.utils.UserDao
import com.yange.accountbook.utils.showToast
import java.util.*

class MineFragment : BaseFragment<MineFragmentLayoutBinding>() {

    private lateinit var dialog: DatePickerDialog
    override fun initView() {
        initListener()
        getDay()
        activity?.let { initVersion(it) }
        binding.tvEnable.isChecked = UserDao.getUserInfo().periodStatus;
    }

    override fun initData() {

    }
    private fun initVersion(mContext: Context){
        val versionCode = mContext.packageManager.getPackageInfo(mContext.packageName,0).versionCode
        val userVersion = UserDao.getUserInfo().version
        if (userVersion > versionCode ){
            binding.version.visibility = View.GONE;
            binding.install.visibility = View.VISIBLE
            binding.install.setOnClickListener{
                // 核心代码
                val uri = Uri.parse(UserDao.getUserInfo().apkUrl);
                startActivity(Intent(Intent.ACTION_VIEW, uri));
            }
        } else {
            binding.version.setText(mContext.packageManager.getPackageInfo(mContext.packageName,0).versionName)
            binding.version.setOnClickListener{
                refreshUserInfo()
            }
        }
    }

    private fun initListener() {
        val calendar: Calendar = Calendar.getInstance()

        binding.tvEnable.setOnCheckedChangeListener({ buttonView, isChecked ->
            setPeriodStatus(isChecked)
        })

        binding.layoutDay.setOnClickListener {
            dialog = activity?.let { it1 ->
                DatePickerDialog(
                    it1,
                    { p0, year, month, day ->
                        setDay(day)
                    },
                    calendar.get(Calendar.YEAR),
                    calendar.get(Calendar.MONTH),
                    calendar.get(Calendar.DAY_OF_MONTH)
                )
            }!!
            dialog.show()
        }
        binding.layoutModule.setOnClickListener {
            activity?.startActivity(Intent(activity, AccountModuleActivity().javaClass))
        }
        binding.layoutItem.setOnClickListener {
            activity?.let { it1 -> DetailedManageActivity.start(it1) }
        }

        binding.btnOutLogin.setOnClickListener {
            UserDao.token = ""
            startActivity(Intent(activity, LoginActivity().javaClass))
        }
    }

    /**
     * 获取账期
     */
    private fun getDay() {
        RetrofitClient.getInstance().invokeGet(activity, Api.GET_DAY, mapOf())
            .subscribe(object : RecObserver<BaseResponse<Int>>(activity, false, false) {
                override fun onSuccess(t: BaseResponse<Int>?) {
                    if (t?.data != null) {
                        binding.tvDay.text = "每月" + t.data.toString() + "日"
                    }
                }

                override fun onFail(msg: String, code: Int) {
                    showToast(msg)
                }
            })
    }

    private fun setPeriodStatus(enable: Boolean) {
        RetrofitClient.getInstance().setPeriodStatus(activity, enable)
            .subscribe(object : RecObserver<BaseResponse<Int>>(activity, false, false) {
                override fun onSuccess(t: BaseResponse<Int>?) {
                    refreshUserInfo()
                }

                override fun onFail(msg: String, code: Int) {
                    showToast(msg)
                }
            })
    }

    /**
     * 设置账期
     */
    private fun setDay(day: Int) {
        RetrofitClient.getInstance().setDay(activity, day)
            .subscribe(object : RecObserver<BaseResponse<Any>>(activity, false, false) {
                override fun onSuccess(t: BaseResponse<Any>?) {
                    binding.tvDay.text = "每月" + day.toString() + "日"
                    refreshUserInfo()
                }

                override fun onFail(msg: String, code: Int) {
                    showToast(msg)
                }
            })
    }

    private fun refreshUserInfo() {
        RetrofitClient.getInstance().invokeGet(activity, Api.USER_INFO)
            .subscribe(object : RecObserver<BaseResponse<UserInfoEntity>>(activity, true, false) {
                override fun onSuccess(t: BaseResponse<UserInfoEntity>?) {
                    if (t != null) {
                        UserDao.info = Gson().toJson(t.data)
                        activity?.let { initVersion(it) }
                    }
                }

                override fun onFail(msg: String, code: Int) {
                    showToast(msg)
                }
            })
    }

}